﻿using System;
using System.Globalization;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.Account;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// /
	/// </summary>
	public class IsMemberInfoCompleteCommand : IRequest<BaseResult<bool>>
	{
		/// <summary>
		/// 
		/// </summary>
		public string Mobile { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public IsMemberInfoCompleteCommand()
		{
		}
	}

	/// <summary>
	/// 
	/// </summary>
	public class IsMemberInfoCompleteCommandHandler : BaseCommandHandler, IRequestHandler<IsMemberInfoCompleteCommand, BaseResult<bool>>
	{
		private readonly IServiceScopeFactory _scopeFactory;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="serviceScopeFactory"></param>
		/// <param name="netICService"></param>
		/// <param name="httpClientFactory"></param>
		/// <param name="settings"></param>
		public IsMemberInfoCompleteCommandHandler(IServiceScopeFactory serviceScopeFactory, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
		{

			_scopeFactory = serviceScopeFactory;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<bool>> Handle(IsMemberInfoCompleteCommand request, CancellationToken cancellationToken)
		{
			using var scope = _scopeFactory.CreateScope();
			//var _MemberService = scope.ServiceProvider.GetRequiredService<IMemberService>();
			var _cardService = scope.ServiceProvider.GetRequiredService<IMemberCardService>();
			var _memberService = scope.ServiceProvider.GetRequiredService<IMemberService>();
			var url = "v3/MemberCard/GetCardMember";
			var result = await PostThirdApiAsync<MemberInfoResponse>(url, JsonConvert.SerializeObject(request)).ConfigureAwait(false);
			if (result.Code == 0) {
				 MemberInfoResponse memberInfoResponse=result.Content;
				if(memberInfoResponse!=null) {
					if(memberInfoResponse.CardNo is not { Length: > 1 }) {
						var cardinfo = await _cardService.FindAsync<ICasaMielSession>(request.Mobile, false).ConfigureAwait(false);
						if (cardinfo != null) {
							memberInfoResponse.CardNo = cardinfo.CardNO;
							memberInfoResponse.CardType = Convert.ToInt16(cardinfo.CardType);
							memberInfoResponse.BindSource = cardinfo.Source == 15 ? 1 : 2;
							memberInfoResponse.BindTime = cardinfo.BindTime;
							await PostThirdApiAsync<string>("v3/MemberCard/SaveCardMember", JsonConvert.SerializeObject(memberInfoResponse)).ConfigureAwait(false);
						}
					}
					if(memberInfoResponse.RealName is {Length:>0}
					&& memberInfoResponse.City is { Length: > 2 }
					&& memberInfoResponse.Provice is{Length:>2}
					&& memberInfoResponse.District is {Length:>1}
					&& memberInfoResponse.LiveWay is {Length:>1}
					&& memberInfoResponse.StoreName is {Length:>2}
					&& memberInfoResponse.StoreDistance is {Length:>1}) {
						return new BaseResult<bool>(true, 0, "");
					}

				} else {
					var memberinfo = await _memberService.FindAsync<ICasaMielSession>(request.Mobile, false).ConfigureAwait(false);
					memberInfoResponse = new MemberInfoResponse();
					memberInfoResponse.Mobile = request.Mobile;
					memberInfoResponse.RegisterTime = memberinfo.CreateDate.Value;
					memberInfoResponse.RealName = memberinfo.Nick;
					memberInfoResponse.InvitationCode = memberinfo.InvitationCode;
					if (memberinfo.Birthday.HasValue) {
						memberInfoResponse.Birthday = memberinfo.Birthday.Value;
					}
				    var cardinfo = await _cardService.FindAsync<ICasaMielSession>(request.Mobile, false).ConfigureAwait(false);
					if (cardinfo != null) {
						memberInfoResponse.CardNo = cardinfo.CardNO;
						memberInfoResponse.CardType = Convert.ToInt16(cardinfo.CardType,CultureInfo.CurrentCulture);
						memberInfoResponse.BindSource = cardinfo.Source == 15 ? 1 : 2;
						memberInfoResponse.BindTime = cardinfo.BindTime;
					}
					await PostThirdApiAsync<string>("v3/MemberCard/SaveCardMember", JsonConvert.SerializeObject(memberInfoResponse)).ConfigureAwait(false);
				}
			}
			return new BaseResult<bool>(false, 0, "");
		}
	}
}